package com.pfzy.lib.net;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pfzy.lib.net.convert.CCConverterFactory;
import com.pfzy.lib.net.convert.NullOnEmptyConverterFactory;
import com.pfzy.lib.net.interceptor.HttpHeaderInterceptor;
import com.pfzy.lib.net.interceptor.LoggingInterceptor;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * 网络管理
 */
public class ServiceManager {
    private final String TAG = ServiceManager.class.getSimpleName();
    private static final int DEFAULT_TIME_OUT = 20;//超时时间 5s
    public static boolean mDebugMode = false;
    private OkHttpClient.Builder mOkHttpClientBuilder;
    private Retrofit.Builder mRetrofitBuilder;

    /**
     * 获取单例
     */
    public static ServiceManager getInstance() {
        return ServiceManagerHolder.INSTANCE;
    }
    /**
     * 在访问 时创建单例
     */
    private static class ServiceManagerHolder {
        private static final ServiceManager INSTANCE = new ServiceManager();
    }

    ServiceManager() {
        initOkHttpClientBuilder();

        Gson gson = new GsonBuilder().serializeNulls().create();
        mRetrofitBuilder = new Retrofit.Builder()
                .client(getOkHttpClientBuilder().build())
                // 用来创建CallAdapter对象，CallAdapter对象可以用来构建请求参数。
                // 获取CallAdapter对象。通过CallAdapter对象就可以成功获取到请求相关的参数，以及一切你准备在请求开始之前的操作。
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                // 向服务器获取和发送数据需要添加转换器工厂，只是为了改造可以将JSON数据（从服务器获取）转换为Java（模型）对象（POJO）
                // 如果远程数据类型是 XML，则需要添加SimpleXmlConverterFactory
//                .addConverterFactory(GsonConverterFactory.create(gson))
//                .addConverterFactory(JsonConverterFactory.create())
                .addConverterFactory(CCConverterFactory.create())
                .addConverterFactory(new NullOnEmptyConverterFactory());
    }

    private void initOkHttpClientBuilder(){
        mOkHttpClientBuilder = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS) // 连接超时时间
                .writeTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)    // 读操作超时时间
                .addInterceptor(new LoggingInterceptor())           // 日志拦截器
                .addInterceptor(new HttpHeaderInterceptor());
//                .retryOnConnectionFailure(true)// 当连接失败，尝试重连。
//                .addNetworkInterceptor(new HttpCacheInterceptor())// 开启请求头
//                // .sslSocketFactory(SslContextFactory.getSSLSocketFactoryForTwoWay())  // https认证 如果要使用https且为自定义证书 可以去掉这两行注释，并自行配制证书。
//                // .hostnameVerifier(new SafeHostnameVerifier())
//                .cache(cache);
    }

    private OkHttpClient.Builder getOkHttpClientBuilder(){
        return mOkHttpClientBuilder;
    }

    public <T> T create(Class<T> cls, String baseUrl) {
        Retrofit retrofit = mRetrofitBuilder.baseUrl(baseUrl).build();
        return retrofit.create(cls);
    }
}
